<?php session_start();?>
<meta http-equiv="content-type" content="text/html;charset=utf-8"/>
<?php 
ini_set('date.timezone','Asia/Shanghai');
//error_reporting(E_ERROR);

require_once "../lib/WxPay.Api.php";
require_once "WxPay.JsApiPay.php";
require_once 'log.php';

$hostname = WxPayConfig::HOST;
$username = WxPayConfig::USERNAME;
$password = WxPayConfig::PASSWORDE;
$database = WxPayConfig::DATABASSE;
$con = mysql_connect($hostname,$username,$password);
if (!$con)
{
	die('Could not connect: ' . mysql_error());
}

mysql_select_db($database, $con);
$sql = "SELECT * FROM mifi_device WHERE device_sn = ".$_GET['device_sn']."";
$result = mysql_query($sql);
$row = mysql_fetch_array($result);


//初始化日志
$logHandler= new CLogFileHandler("../logs/".date('Y-m-d').'.log');
$log = Log::Init($logHandler, 15);

//①、获取用户openid
$tools = new JsApiPay();
$openId = $tools->GetOpenid();
$_SESSION['openid'] = $openId;

if($row){
	$data['order_on'] = time().rand(100,999); //订单编号
	$data['starttime'] = date("YmdHis"); //下单时间
	$data['paystate'] = '0';      //支付状态 0未支付  1已支付  
	$data['goods_on'] = $_GET['rechargepackageid']; //套餐
	$data['packageid'] = $_GET['rechargepackageid'];  //套餐packageid 
	$data['user_id'] = $_GET['rechargetuser'];
	$data['device_id'] = $_GET['device_sn'];
	$data['order_money'] = $_GET['rechargeprice'];
	$url = $_GET['url'];
	
	$sql_into = "INSERT INTO `mifi_order` (`order_on`, `starttime`, `endtime`, `paystate`, `goods_on`, `user_id`, `device_id`,`order_money`) VALUES ('".$data['order_on']."', '".$data['starttime']."','',0,'".$data['goods_on']."', '".$data['user_id']."', '".$data['device_id']."', '".$data['order_money']."')";
	$result_into = mysql_query($sql_into);
}

mysql_close($con);

//②、统一下单   $_GET['rechargeprice']*100 
$input = new WxPayUnifiedOrder();
$input->SetBody($_GET['rechargeflow']);
$input->SetAttach("test1");
$input->SetOut_trade_no($data['order_on'].$data['starttime']);
$input->SetTotal_fee($_GET['rechargeprice']*100);
//$input->SetTotal_fee('1');
$input->SetTime_start(date("YmdHis"));
//$input->SetTime_expire(date("YmdHis"), time() + 600);
$input->SetGoods_tag("test2");
$input->SetNotify_url("http://".$_SERVER['HTTP_HOST']."/weixin/example/notify.php");
$input->SetTrade_type("JSAPI");
$input->SetOpenid($openId);

$order = WxPayApi::unifiedOrder($input);

$jsApiParameters = $tools->GetJsApiParameters($order);

//获取共享收货地址js函数参数
$editAddress = $tools->GetEditAddressParameters();

//③、在支持成功回调通知中处理成功之后的事宜，见 notify.php
/**
 * 注意：
 * 1、当你的回调地址不可访问的时候，回调通知会失败，可以通过查询订单来确认支付是否成功
 * 2、jsapi支付时需要填入用户openid，WxPay.JsApiPay.php中有获取openid流程 （文档可以参考微信公众平台“网页授权接口”，
 * 参考http://mp.weixin.qq.com/wiki/17/c0f37d5704f0b64713d5d2c37b468d75.html）
 */
?>

<html>
<head>
	<meta http-equiv="content-type" content="text/html;charset=utf-8"/>
    <title><?php echo $_GET['rechargeflow']; ?></title>
    <link href="../../mobile/css/swiper.min.css" rel="stylesheet"/>
    <link href="../../mobile/css/public.css" rel="stylesheet"/>
    <link href="../../mobile/css/main.css" rel="stylesheet"/>
    <link href="../../mobile/css/style.css" rel="stylesheet"/>
    <script src="http://www.jq22.com/jquery/jquery-1.9.1.js"></script>
    <script src="../../mobile/js/mobile-util.js"></script>
    <script src="../../mobile/js/layer/layer.js"></script>
    <script src="../../mobile/js/public.js"></script>
	
	<style>
		.comfimprice{
			padding: 1.5rem 0;
			text-align: center;
			color: #ED5E64;
			background: white;
		}
		.comfiminfo{
			margin-top: .5rem;
			padding: .5rem;
			background: white;
		}
		.comfiminfo li{
			padding: .5rem 0;
		}
		body{
			background: #EDEDED!important;
		}
	</style>

    <script type="text/javascript">
	//调用微信JS api 支付
	/* function jsApiCall() { 
	   WeixinJSBridge.invoke(
	   'getBrandWCPayRequest',
	   <?php echo $jsApiParameters; ?>, 
	   function(res){  
		var msg = res.err_msg; 
		if (msg == "get_brand_wcpay_request:ok") { 
			alert("支付成功，跳转到订单详情页"); 
			//location.href = "/order_detail.php"; 
		} else { 
			if (msg == "get_brand_wcpay_request:cancel") { 
				var err_msg = "您取消了微信支付"; 
			} else if (msg == "get_brand_wcpay_request:fail") { 
				var err_msg = "微信支付失败错误信息：" + res.err_desc; 
			} else { 
				var err_msg = msg + "" + res.err_desc; 
			} 
			show_notice(err_msg); 
		} 
	   } 
	} */
	
	function jsApiCall()
	{
		WeixinJSBridge.invoke(
			'getBrandWCPayRequest',
			<?php echo $jsApiParameters; ?>,
			function(res){
				if (res.err_msg == "get_brand_wcpay_request:ok"){ 
					location.href = "<?php echo $url; ?>"; 
				}else{
					if (res.err_msg == "get_brand_wcpay_request:cancel") { 
						var err_msg = "您取消了微信支付";
						alert(err_msg);	
					}
				}
			}
		)
	} 

	function callpay()
	{
		if (typeof WeixinJSBridge == "undefined"){
		    if( document.addEventListener ){
		        document.addEventListener('WeixinJSBridgeReady', jsApiCall, false);
		    }else if (document.attachEvent){
		        document.attachEvent('WeixinJSBridgeReady', jsApiCall); 
		        document.attachEvent('onWeixinJSBridgeReady', jsApiCall);
		    }
		}else{
		    jsApiCall();
		}
	}
	
	//获取共享地址
	function editAddress()
	{
		WeixinJSBridge.invoke(
			'editAddress',
			<?php echo $editAddress; ?>,
			function(res){
				var value1 = res.proviceFirstStageName;
				var value2 = res.addressCitySecondStageName;
				var value3 = res.addressCountiesThirdStageName;
				var value4 = res.addressDetailInfo;
				var tel = res.telNumber;
				if(tel == ok){
					//alert( 33333);
				}
				/* alert(value1 + value2 + value3 + value4 + ":" + tel); */
			}
		);
	}
	
	window.onload = function(){
		if (typeof WeixinJSBridge == "undefined"){
		    if( document.addEventListener ){
		        document.addEventListener('WeixinJSBridgeReady', editAddress, false);
		    }else if (document.attachEvent){
		        document.attachEvent('WeixinJSBridgeReady', editAddress); 
		        document.attachEvent('onWeixinJSBridgeReady', editAddress);
		    }
		}else{
			editAddress();
		}
	};
	
	</script>
</head>
<body>

	<header class="mui-bar mui-bar-nav indexheader flex">
		<div class="headerlogo" onclick="back()">
			<i class="iconfont backbtn">&#xe602;</i>
		</div>

		<div class="headertitle">
			<p>继续充值</p>
		</div>

		<div class="headerright">

		</div>

	</header>
	
	<main class="realmain">
    	<div class="comfimprice">
    		<span style="font-size: 1rem">&yen</span> <span style="font-size: 1.5rem"><?php echo $_GET['rechargeprice']; ?>元</span>
    	</div>

    	<ul class="comfiminfo">
    		<li class="flex">

    			<div class="flex-1 te-le" style="font-size:.6rem">
    				充值套餐
    			</div>

    			<div class="flex-1 te-ri" style="font-size:.6rem">
    				<?php echo $_GET['rechargeflow']; ?>
    			</div>
    		</li>
    	</ul>


    	<div class="ma-speen-5">
    		<input type="button" value="确认付款" onclick="callpay()" class="rechargebtn">
    	</div>



    </main>

    <!--<font color="#9ACD32"><b>该笔订单支付金额为<span style="color:#f00;font-size:50px"></span>钱</b></font><br/><br/>-->
	<div align="center" style="display:none">
		<button style="width:210px; height:50px; border-radius: 15px;background-color:#FE6714; border:0px #FE6714 solid; cursor: pointer;  color:white;  font-size:16px;" type="button"  >立即支付</button>
	</div>
</body>
</html>
